package us.team.openAnAppAtRandom;

import android.os.Bundle;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import java.util.List;
import java.util.Random;
import java.util.ArrayList;
import android.widget.TextView;
import android.net.Uri;
import android.app.AlertDialog;
import android.os.Environment;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.content.DialogInterface;
import android.widget.Toast;
import android.Manifest;
import android.content.pm.ApplicationInfo;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.Switch;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import us.team.openAnAppAtRandom.model.AppItem;
import us.team.openAnAppAtRandom.model.AppList;
import us.team.openAnAppAtRandom.util.AppListManager;
import android.provider.Settings;
import android.media.projection.MediaProjectionManager;

public class MainActivity extends AppCompatActivity {
    private AppListManager appListManager;
    private static int selectedListPosition = -1; // -1表示"全部"，使用静态变量保持状态
    private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private boolean isAutoMode = false;
    private Handler autoHandler = new Handler();
    private Runnable autoRunnable;
    private static final int OVERLAY_PERMISSION_REQUEST_CODE = 1001;
    private static final int SCREEN_RECORD_REQUEST_CODE = 1002;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 初始化应用清单管理器
        appListManager = new AppListManager(this);
        
        Button btn = findViewById(R.id.btn_random_open_app);
        btn.setOnClickListener(v -> selectRandomApp());
        
        Button exportBtn = findViewById(R.id.btn_export_apps);
        exportBtn.setOnClickListener(v -> checkPermissionAndExportApps());
        
        Button manageListsBtn = findViewById(R.id.btn_manage_lists);
        manageListsBtn.setOnClickListener(v -> openAppListsActivity());
        
        Button backToHomeBtn = findViewById(R.id.btn_back_to_home);
        backToHomeBtn.setOnClickListener(v -> backToHomeScreen());
        
        // 设置悬浮窗开关
        Switch floatingWindowSwitch = findViewById(R.id.switch_floating_window);
        floatingWindowSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 开启悬浮窗
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (!Settings.canDrawOverlays(MainActivity.this)) {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                    Uri.parse("package:" + getPackageName()));
                            startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE);
                            // 如果没有权限，先关闭开关
                            floatingWindowSwitch.setChecked(false);
                        } else {
                            startFloatingWindowService();
                        }
                    } else {
                        startFloatingWindowService();
                    }
                } else {
                    // 关闭悬浮窗
                    stopFloatingWindowService();
                }
            }
        });
        
        TextView link = findViewById(R.id.link_developer);
        link.setOnClickListener(v -> openDeveloperLink());

        // 超链接风格的“设置”和“App Usage”
        TextView linkSettings = findViewById(R.id.link_settings);
        TextView linkAppUsage = findViewById(R.id.link_app_usage);
        if (linkSettings != null) {
            linkSettings.setOnClickListener(v -> {
                // 优先按包名启动 com.android.settings，若失败则回退到系统设置界面
                Intent launch = getPackageManager().getLaunchIntentForPackage("com.android.settings");
                if (launch != null) {
                    startActivity(launch);
                } else {
                    try {
                        startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, "无法打开设置", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        if (linkAppUsage != null) {
            linkAppUsage.setOnClickListener(v -> {
                Intent launch = getPackageManager().getLaunchIntentForPackage("com.a0soft.gphone.uninstaller");
                if (launch != null) {
                    startActivity(launch);
                } else {
                    Toast.makeText(MainActivity.this, "未安装 App Usage", Toast.LENGTH_SHORT).show();
                }
            });
        }
        
        // 设置清单下拉选择器
        setupAppListSpinner();
        
        // 初始化自动开关
        Switch autoSwitch = findViewById(R.id.switch_auto_random);
        
        // 创建自动运行的Runnable
        autoRunnable = new Runnable() {
            @Override
            public void run() {
                if (isAutoMode) {
                    selectRandomApp();
                    // 每3.5秒触发一次，避免与确认倒计时冲突
                    autoHandler.postDelayed(this, 3500);
                }
            }
        };
        
        // 设置开关监听器
        autoSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAutoMode = isChecked;
                
                if (isChecked) {
                    // 开启自动模式，延迟500毫秒后开始
                    autoHandler.postDelayed(autoRunnable, 500);
                    Toast.makeText(MainActivity.this, "已开启自动模式", Toast.LENGTH_SHORT).show();
                } else {
                    // 关闭自动模式，移除回调
                    autoHandler.removeCallbacks(autoRunnable);
                    Toast.makeText(MainActivity.this, "已关闭自动模式", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra("start_screen_record", false)) {
            startScreenRecording();
        }
    }
    
    private void checkPermissionAndExportApps() {
        // 获取导出按钮并禁用它
        Button exportBtn = findViewById(R.id.btn_export_apps);
        exportBtn.setEnabled(false);
        exportBtn.setText("导出中...");
        
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
            
            // 如果没有权限，恢复按钮状态
            exportBtn.setEnabled(true);
            exportBtn.setText("导出所有应用信息");
        } else {
            exportAllAppsInfo();
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                exportAllAppsInfo();
            } else {
                Toast.makeText(this, "需要存储权限才能导出应用信息", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OVERLAY_PERMISSION_REQUEST_CODE) {
            Switch floatingWindowSwitch = findViewById(R.id.switch_floating_window);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    floatingWindowSwitch.setChecked(true);
                    startFloatingWindowService();
                } else {
                    floatingWindowSwitch.setChecked(false);
                    Toast.makeText(this, "需要悬浮窗权限才能使用此功能", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (requestCode == SCREEN_RECORD_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "录屏已开始", Toast.LENGTH_SHORT).show();
                // 录屏权限获取成功，系统会自动开始录屏
                finish(); // 关闭Activity，返回到之前的界面
            } else {
                Toast.makeText(this, "录屏权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void startFloatingWindowService() {
        Intent serviceIntent = new Intent(this, FloatingWindowService.class);
        startService(serviceIntent);
        Toast.makeText(this, "悬浮窗已启动", Toast.LENGTH_SHORT).show();
    }
    
    private void stopFloatingWindowService() {
        Intent serviceIntent = new Intent(this, FloatingWindowService.class);
        stopService(serviceIntent);
        Toast.makeText(this, "悬浮窗已关闭", Toast.LENGTH_SHORT).show();
    }

    private void startScreenRecording() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            MediaProjectionManager mediaProjectionManager = 
                (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
            Intent screenCaptureIntent = mediaProjectionManager.createScreenCaptureIntent();
            startActivityForResult(screenCaptureIntent, SCREEN_RECORD_REQUEST_CODE);
        } else {
            Toast.makeText(this, "您的设备不支持录屏功能", Toast.LENGTH_SHORT).show();
        }
    }

    private void selectRandomApp() {
        // 如果选择了特定清单
        if (selectedListPosition >= 0 && selectedListPosition < appListManager.getAppLists().size()) {
            AppList selectedList = appListManager.getAppLists().get(selectedListPosition);
            if (selectedList.size() > 0) {
                int idx = new Random().nextInt(selectedList.size());
                AppItem selectedApp = selectedList.getApps().get(idx);
                showConfirmationDialog(selectedApp.getAppName(), selectedApp.getPackageName());
            } else {
                Toast.makeText(this, "所选清单为空，请先添加应用", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 从所有应用中随机选择
            PackageManager pm = getPackageManager();
            List<PackageInfo> packages = pm.getInstalledPackages(0);
            // 过滤掉自身和系统应用
            List<PackageInfo> userApps = new java.util.ArrayList<>();
            for (PackageInfo pkg : packages) {
                Intent launchIntent = pm.getLaunchIntentForPackage(pkg.packageName);
                if (launchIntent != null && !pkg.packageName.equals(getPackageName())) {
                    userApps.add(pkg);
                }
            }
            if (userApps.size() > 0) {
                int idx = new Random().nextInt(userApps.size());
                PackageInfo selectedPkg = userApps.get(idx);
                String pkgName = selectedPkg.packageName;
                String appName = "";
                try {
                    ApplicationInfo appInfo = pm.getApplicationInfo(pkgName, 0);
                    appName = pm.getApplicationLabel(appInfo).toString();
                } catch (NameNotFoundException e) {
                    appName = pkgName;
                }
                
                showConfirmationDialog(appName, pkgName);
            }
        }
    }
    
    private void showConfirmationDialog(String appName, String packageName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        
        // 使用自定义布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_confirmation, null);
        builder.setView(dialogView);
        
        // 设置标题和消息
        TextView titleView = dialogView.findViewById(R.id.dialog_title);
        TextView messageView = dialogView.findViewById(R.id.dialog_message);
        titleView.setText(appName);
        messageView.setText("？");
        
        // 创建对话框
        final AlertDialog dialog = builder.create();
        
        // 设置对话框显示在底部
        if (dialog.getWindow() != null) {
            android.view.WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
            layoutParams.gravity = android.view.Gravity.BOTTOM;
            layoutParams.y = 400; // 距离底部的像素距离
            dialog.getWindow().setAttributes(layoutParams);
        }
        
        // 获取按钮引用
        final Button confirmButton = dialogView.findViewById(R.id.btn_confirm);
        Button changeButton = dialogView.findViewById(R.id.btn_change);
        Button uninstallButton = dialogView.findViewById(R.id.btn_uninstall);
        Button closeButton = dialogView.findViewById(R.id.btn_close);
        
        // 创建倒计时器
        final CountDownTimer countDownTimer = new CountDownTimer(3000, 1000) {
            int secondsRemaining = 3;
            
            @Override
            public void onTick(long millisUntilFinished) {
                if (confirmButton != null && dialog.isShowing()) {
                    confirmButton.setText("确认(" + secondsRemaining + "秒)");
                }
                secondsRemaining--;
            }
            
            @Override
            public void onFinish() {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                    openApp(packageName);
                }
            }
        };
        
        // 设置按钮点击事件
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDownTimer.cancel(); // 立即停止倒计时
                dialog.dismiss();
                openApp(packageName);
            }
        });
        
        changeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDownTimer.cancel(); // 立即停止倒计时
                dialog.dismiss();
                selectRandomApp();
            }
        });
        
        uninstallButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDownTimer.cancel(); // 立即停止倒计时
                openAppDetails(packageName);
            }
        });
        
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDownTimer.cancel(); // 立即停止倒计时
                dialog.dismiss();
                // 关闭自动模式
                if (isAutoMode) {
                    Switch autoSwitch = findViewById(R.id.switch_auto_random);
                    autoSwitch.setChecked(false);
                }
            }
        });
        
        // 在自动模式下禁用"换一个"按钮
        if (isAutoMode) {
            changeButton.setEnabled(false);
        }
        
        dialog.show();
        
        // 启动倒计时器
        countDownTimer.start();
    }
    
    private void openApp(String packageName) {
        PackageManager pm = getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(packageName);
        if (intent != null) {
            startActivity(intent);
            
            // 如果是自动模式，在打开应用后延迟500毫秒再次触发随机选择
            if (isAutoMode) {
                // 移除之前的回调，避免重复触发
                autoHandler.removeCallbacks(autoRunnable);
                // 延迟500毫秒后再次触发
                autoHandler.postDelayed(autoRunnable, 500);
            }
        }
    }
    
    private void openAppDetails(String packageName) {
        try {
            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "无法打开应用详情页面", Toast.LENGTH_SHORT).show();
        }
    }

    private void exportAllAppsInfo() {
        final Button exportBtn = findViewById(R.id.btn_export_apps);
        
        // 显示正在导出的提示
        Toast.makeText(this, "正在导出应用信息，请稍候...", Toast.LENGTH_SHORT).show();
        
        // 在后台线程中执行导出操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    PackageManager pm = getPackageManager();
                    List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS | 
                                                                        PackageManager.GET_ACTIVITIES | 
                                                                        PackageManager.GET_SERVICES | 
                                                                        PackageManager.GET_PROVIDERS);
                    
                    File directory = new File(Environment.getExternalStorageDirectory(), "A_gwd_App_output");
                    if (!directory.exists()) {
                        directory.mkdirs();
                    }
                    
                    // 导出完整版应用信息
                    File outputFile = new File(directory, "all_app_info.txt");
                    FileWriter writer = new FileWriter(outputFile);
                    
                    writer.write("===== 所有应用信息（完整版）=====\n\n");
                    
                    for (PackageInfo pkg : packages) {
                        writer.write("应用名称: ");
                        String appName = "未知";
                        try {
                            ApplicationInfo appInfo = pm.getApplicationInfo(pkg.packageName, 0);
                            appName = pm.getApplicationLabel(appInfo).toString();
                            writer.write(appName);
                        } catch (Exception e) {
                            writer.write("未知");
                        }
                        writer.write("\n");
                        
                        writer.write("包名: " + pkg.packageName + "\n");
                        writer.write("版本名: " + pkg.versionName + "\n");
                        writer.write("版本号: " + pkg.versionCode + "\n");
                        writer.write("安装时间: " + new java.util.Date(pkg.firstInstallTime) + "\n");
                        writer.write("最后更新时间: " + new java.util.Date(pkg.lastUpdateTime) + "\n");
                        
                        // 应用权限
                        writer.write("权限列表:\n");
                        if (pkg.requestedPermissions != null) {
                            for (String permission : pkg.requestedPermissions) {
                                writer.write("  - " + permission + "\n");
                            }
                        } else {
                            writer.write("  无权限信息\n");
                        }
                        
                        // 应用类型
                        ApplicationInfo appInfo = pkg.applicationInfo;
                        String appType = ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? 
                            "系统应用" : "用户应用";
                        writer.write("应用类型: " + appType + "\n");
                        
                        writer.write("\n----------------------------\n\n");
                    }
                    
                    writer.close();
                    
                    // 导出简化版应用信息
                    File simpleOutputFile = new File(directory, "all_app_info_simple.txt");
                    FileWriter simpleWriter = new FileWriter(simpleOutputFile);
                    
                    simpleWriter.write("===== 所有应用信息（简化版）=====\n\n");
                    
                    for (PackageInfo pkg : packages) {
                        String appName = "未知";
                        try {
                            ApplicationInfo appInfo = pm.getApplicationInfo(pkg.packageName, 0);
                            appName = pm.getApplicationLabel(appInfo).toString();
                        } catch (Exception e) {
                            // 使用默认值
                        }
                        
                        simpleWriter.write("应用名称: " + appName + "\n");
                        simpleWriter.write("包名: " + pkg.packageName + "\n");
                        simpleWriter.write("版本名: " + pkg.versionName + "\n");
                        simpleWriter.write("版本号: " + pkg.versionCode + "\n");
                        
                        // 应用类型
                        ApplicationInfo appInfo = pkg.applicationInfo;
                        String appType = ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? 
                            "系统应用" : "用户应用";
                        simpleWriter.write("应用类型: " + appType + "\n");
                        
                        simpleWriter.write("\n----------------------------\n\n");
                    }
                    
                    simpleWriter.close();
                    
                    // 在UI线程中更新界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, 
                                "应用信息已导出到: " + directory.getAbsolutePath(), 
                                Toast.LENGTH_LONG).show();
                            
                            // 导出完成后，恢复按钮状态但保持禁用
                            exportBtn.setText("导出完成");
                        }
                    });
                    
                } catch (final IOException e) {
                    // 在UI线程中显示错误信息
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, 
                                "导出失败: " + e.getMessage(), 
                                Toast.LENGTH_SHORT).show();
                            
                            // 发生错误时，恢复按钮状态
                            exportBtn.setEnabled(true);
                            exportBtn.setText("导出所有应用信息");
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void openDeveloperLink() {
        String url = "https://gitee.com/gwdcode"; // TODO: 填写实际网址
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
    }
    
    private void openAppListsActivity() {
        Intent intent = new Intent(this, AppListsActivity.class);
        startActivity(intent);
    }
    
    /**
     * 返回到Android桌面
     */
    private void backToHomeScreen() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    
    /**
     * 设置应用清单下拉选择器
     */
    private void setupAppListSpinner() {
        Spinner spinner = findViewById(R.id.spinner_app_lists);
        
        // 准备下拉列表数据
        List<String> listNames = new ArrayList<>();
        listNames.add("全部应用"); // 默认选项
        
        for (AppList list : appListManager.getAppLists()) {
            listNames.add(list.getName() + " (" + list.size() + "个应用)");
        }
        
        // 创建适配器，使用自定义布局
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
            this, R.layout.spinner_item, listNames);
        adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        
        // 设置适配器
        spinner.setAdapter(adapter);
        
        // 设置下拉列表宽度为屏幕宽度
        spinner.setDropDownWidth(android.view.ViewGroup.LayoutParams.MATCH_PARENT);
        
        // 计算要选择的位置
        int positionToSelect = 0; // 默认选择"全部应用"
        if (selectedListPosition >= 0 && selectedListPosition < appListManager.getAppLists().size()) {
            positionToSelect = selectedListPosition + 1; // +1 是因为第一项是"全部应用"
        }
        
        // 设置选中的项
        spinner.setSelection(positionToSelect);
        
        // 设置选择监听器
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // position 0 是"全部应用"
                selectedListPosition = position - 1; // -1 表示"全部"
            }
            
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedListPosition = -1; // 默认为"全部"
            }
        });
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 重新初始化应用清单管理器，确保获取最新数据
        appListManager = new AppListManager(this);
        // 刷新清单下拉选择器
        setupAppListSpinner();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理自动模式的Handler回调，避免内存泄漏
        if (autoHandler != null && autoRunnable != null) {
            autoHandler.removeCallbacks(autoRunnable);
        }
    }
}
